package com.abai.doubi.server.controller;

import com.abai.doubi.constants.JwtClaimsConstant;
import com.abai.doubi.entity.Result;
import com.abai.doubi.entity.dto.LoginDTO;
import com.abai.doubi.entity.pojo.User;
import com.abai.doubi.entity.vo.LoginVO;
import com.abai.doubi.server.properties.JwtProperties;
import com.abai.doubi.server.service.IUserService;
import com.abai.doubi.utils.ContextUtil;
import com.abai.doubi.utils.JwtUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

//@CrossOrigin("*")
@RestController
@RequestMapping("/user")
@Slf4j
@Tag(name = "用户接口", description = "用户相关接口")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "通过手机号或邮箱注册用户")
    public Result register(@RequestBody LoginDTO loginDto){
        String phoneOrEmail = loginDto.getAmount();
        String password = loginDto.getPassword();
        String phoneRegex = "^1[3-9]\\d{9}$";
        String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
        if (!phoneOrEmail.matches(phoneRegex) && !phoneOrEmail.matches(emailRegex)) {
            return Result.error("请输入有效的手机号或邮箱");
        }
        if (phoneOrEmail.matches(phoneRegex)){
            if (userService.lambdaQuery().eq(User::getPhone, phoneOrEmail).one() != null) {
                return Result.error("手机号已存在");
            }
            userService.save(User.builder().username(phoneOrEmail).phone(phoneOrEmail).password(password).build());
        }else if(phoneOrEmail.matches(emailRegex)){
            if (userService.lambdaQuery().eq(User::getEmail, phoneOrEmail).one() != null) {
                return Result.error("邮箱已存在");
            }
            userService.save(User.builder().username(phoneOrEmail).email(phoneOrEmail).password(password).build());
        }
        // 其他注册逻辑
        return Result.success();
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "通过手机号或邮箱登录")
    public Result<LoginVO> login(@RequestBody LoginDTO loginDto){
        String phoneOrEmail = loginDto.getAmount();
        String password = loginDto.getPassword();
        log.info("登录参数:{},{}", phoneOrEmail,password);
        String phoneRegex = "^1[3-9]\\d{9}$";
        String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
        if (!phoneOrEmail.matches(phoneRegex) && !phoneOrEmail.matches(emailRegex)) {
            return Result.error("请输入有效的手机号或邮箱");
        }
        User loginUser = null;
        if (phoneOrEmail.matches(phoneRegex)){
            loginUser = userService.lambdaQuery().eq(User::getPhone, phoneOrEmail).eq(User::getPassword, password).one();
        }else if(phoneOrEmail.matches(emailRegex)){
            loginUser = userService.lambdaQuery().eq(User::getEmail, phoneOrEmail).eq(User::getPassword, password).one();
        }
        if (loginUser == null) {
            return Result.error("用户名或密码错误");
        }else{
            ContextUtil.setCurrentId(loginUser.getId());
            log.info("登录成功:{}", loginUser.getId());
            log.info("登录成功检验:{}", ContextUtil.getCurrentId());
            //发放jwt
            HashMap<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID, loginUser.getId());
            String jwt = JwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), claims);
            LoginVO loginVO = LoginVO.builder().id(loginUser.getId()).username(loginUser.getUsername()).token(jwt).build();
            return Result.<LoginVO>builder()
                    .code(Result.SUCCESS_CODE)
                    .data(loginVO)
                    .build();
        }
    }

    @PutMapping("/update")
    @Operation(summary = "用户修改信息", description = "修改个人资料")
    public Result updateInfo(@RequestBody User user){
        boolean update = userService.updateById(user);
        if (update) {
            return Result.success("更新成功");
        }else{
            return Result.error("更新失败");
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询个人信息", description = "查看个人资料")
    @Parameters({
        @Parameter(name = "id", description = "用户ID", required = true)
    })
    public Result<User> getUserInfo(@PathVariable Long id){
        User user = userService.getById(id);
        if (user != null) {
            return Result.<User>builder()
                    .code(Result.SUCCESS_CODE)
                    .data(user)
                    .build();
        }else{
            return Result.error("用户不存在");
        }
    }

    @GetMapping("/logOut")
    @Operation(summary = "退出登陆", description = "退出登陆")
    public Result<User> logOut(){
        try {
            ContextUtil.removeCurrentId();
            return Result.success("退出成功");
        } catch (Exception e) {
            return Result.error("退出失败");
        }
    }
}
